var express = require('express');
var route = express.Router();
var Category = require('../models/Category')
var Content = require('../models/Content')
route.get('/',function(req,res,next){
    var page = Number(req.query.page || 1)
    var categoryID = req.query.category|| ""
    //每页显示多少条
    var limit = 5
    //总页数
    var  pages = 0
    var where={}
    if(categoryID){
        where.category = categoryID
    }
    // user.count获取数据库数据的总条数
    Content.where(where).count().then(function(count){
        //通过查询回来的总条数计算出总页数
        pages = Math.ceil(count / limit)
        //最大不能小于1
        page = Math.max(page,1)
        //最小不能大于pages
        page = Math.min(page,pages)
        //分页
        var skip = (page-1)*limit
        Content.where(where).find().limit(limit).skip(skip).then(function(conten){
            console.log(conten)
            Category.find().then(function(category){
                res.render('main/index',{
                    userInfo:req.userInfo,
                    contents:conten,
                    categorys:category,
                    count: count,
                    pages: pages,
                    limit: limit,
                    page: page,
                    category:categoryID
                })
            })
        })
        
    })
    //render第二个参数分配给index页面使用
})

route.get('/view',function(req,res,next){
        var contentId = req.query.contentid || '';
        Content.findOne({
            _id: contentId
        }).then(function (content) {
            console.log(content)
            content.views++;
            content.save();
            Category.find().then(function(category){
                res.render('main/view',{
                    userInfo:req.userInfo,
                    content:content,
                    categorys:category,
                })
            })
        });
    
})
module.exports = route